package belka.us.ohostoggleswitch;

import belka.us.ohostoggleswitch.util.ToggleSwitchButton;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.global.configuration.DeviceCapability;
import ohos.global.resource.ResourceManager;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
/**
 * Created by lorenzorigato on 4/1/16.
 */
public abstract class BaseToggleSwitch extends DirectionalLayout implements Component.ClickedListener{//OnClickListener

    public interface OnToggleSwitchChangeListener {
        void onToggleSwitchChangeListener(int position, boolean isChecked);
    }

    protected static class Default {

//        protected static final int ACTIVE_BG_COLOR = R.color.blue;
//        protected static final int INACTIVE_BG_COLOR = R.color.gray_light;
//        protected static final int INACTIVE_TEXT_COLOR = R.color.gray;
//        protected static final int SEPARATOR_COLOR = R.color.gray_very_light;

        protected static final int CORNER_RADIUS_DP = 4;
        protected static final float TEXT_SIZE = 12;
        protected static final float TOGGLE_WIDTH = 64;
    }

    private OnToggleSwitchChangeListener mOnToggleSwitchChangeListener = null;

    private int activeBgColor;
    private int activeTextColor;
    private int inactiveBgColor;
    private int inactiveTextColor;
    private int separatorColor;
    private int textSize;
    private float cornerRadius;
    private float toggleWidth;

    private LayoutScatter mInflater;
    private DirectionalLayout toggleSwitchesContainer;
    private ArrayList<String> mLabels;
    private Context mContext;

    public BaseToggleSwitch(Context context) {
        this(context, null);
    }

    public BaseToggleSwitch(Context context,AttrSet attrSet){
        this(context,attrSet,"");
    }

    public BaseToggleSwitch(Context context, AttrSet attrs,String style) {
        super(context, attrs,style);
        handelAttSet(context,attrs);
    }

    public void handelAttSet(Context context,AttrSet attrs) {
        if (attrs != null) {
            try {
                mContext = context;
                mInflater = (LayoutScatter) LayoutScatter.getInstance(context);
                mInflater.parse(ResourceTable.Layout_widget_toggle_switch, this, true);
                toggleSwitchesContainer = (DirectionalLayout) findComponentById(ResourceTable.Id_toggle_switches_container);

                String centerToggleText = null;
                if (attrs.getAttr("textToggleCenter").isPresent()) {
                    centerToggleText = attrs.getAttr("textToggleCenter").get().getStringValue();//attributes.getString(R.styleable.ToggleSwitchOptions_textToggleCenter);
                }
                String leftToggleText = null;
                if (attrs.getAttr("textToggleLeft").isPresent()) {
                    leftToggleText = attrs.getAttr("textToggleLeft").get().getStringValue();//attributes.getString(R.styleable.ToggleSwitchOptions_textToggleLeft);
                }
                String rightToggleText = null;
                if (attrs.getAttr("textToggleRight").isPresent()) {
                    rightToggleText = attrs.getAttr("textToggleRight").get().getStringValue();//attributes.getString(R.styleable.ToggleSwitchOptions_textToggleRight);
                }

                if (attrs.getAttr("activeBgColor").isPresent()) {
                    this.activeBgColor = attrs.getAttr("activeBgColor").get().getColorValue().getValue();
                } else {
                    this.activeBgColor = getResourceManager().getElement(ResourceTable.Graphic_Color).getColor();
                }
                if (attrs.getAttr("activeTextColor").isPresent()) {
                    this.activeTextColor = attrs.getAttr("activeTextColor").get().getColorValue().getValue();//attributes.getColor(R.styleable.ToggleSwitchOptions_activeTextColor, ContextCompat.getColor(context, Default.ACTIVE_TEXT_COLOR));
                } else {
                    this.activeTextColor = attrs.getAttr("white").get().getColorValue().getValue();
                }
                if (attrs.getAttr("inactiveBgColor").isPresent()) {
                    this.inactiveBgColor = attrs.getAttr("inactiveBgColor").get().getColorValue().getValue();//attributes.getColor(R.styleable.ToggleSwitchOptions_inactiveBgColor, ContextCompat.getColor(context, Default.INACTIVE_BG_COLOR));
                } else {
                    this.inactiveBgColor = attrs.getAttr("gray_light").get().getColorValue().getValue();
                }
                if (attrs.getAttr("inactiveTextColor").isPresent()) {
                    this.inactiveTextColor = attrs.getAttr("inactiveTextColor").get().getColorValue().getValue();//attributes.getColor(R.styleable.ToggleSwitchOptions_inactiveTextColor, ContextCompat.getColor(context, Default.INACTIVE_TEXT_COLOR));
                } else {
                    this.inactiveTextColor = attrs.getAttr("gray").get().getColorValue().getValue();
                }
                if (attrs.getAttr("separatorColor").isPresent()) {
                    this.separatorColor = attrs.getAttr("separatorColor").get().getColorValue().getValue();//attributes.getColor(R.styleable.ToggleSwitchOptions_separatorColor, ContextCompat.getColor(context, Default.SEPARATOR_COLOR));
                } else {
                    this.separatorColor = attrs.getAttr("gray_very_light").get().getColorValue().getValue();
                }

                if (attrs.getAttr("ohos_textSize").isPresent()) {
                    this.textSize = attrs.getAttr("ohos_textSize").get().getDimensionValue();
                } else {
                    this.textSize = attrs.getAttr("textsize").get().getIntegerValue();
                }
                if (attrs.getAttr("toggleWidth").isPresent()) {
                    this.toggleWidth = attrs.getAttr("toggleWidth").get().getDimensionValue();//attributes.getDimension(R.styleable.ToggleSwitchOptions_toggleWidth, dp2px(getContext(), Default.TOGGLE_WIDTH));
                } else {
                    this.toggleWidth = 190;
                }
                if (attrs.getAttr("cornerRadius").isPresent()) {
                    this.cornerRadius = attrs.getAttr("cornerRadius").get().getDimensionValue();//attributes.getDimensionPixelSize(R.styleable.ToggleSwitchOptions_cornerRadius, (int) dp2px(context, Default.CORNER_RADIUS_DP));
                } else {
                   this.cornerRadius = 4;
                }
                HiLog.debug(new HiLogLabel(HiLog.LOG_APP,3,"XYZ"),"center="+centerToggleText+
                        " left="+leftToggleText+" right="+rightToggleText+" toggleWidth="+toggleWidth+" toggleSwitchesContainer="+toggleSwitchesContainer);
                if (leftToggleText != null && !leftToggleText.isEmpty() &&
                        rightToggleText != null && !rightToggleText.isEmpty()) {
                    mLabels = new ArrayList<>();
                    mLabels.add(leftToggleText);
                    if (centerToggleText != null && !centerToggleText.isEmpty())
                        mLabels.add(centerToggleText);
                    mLabels.add(rightToggleText);
                    buildToggleButtons();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            finally {
                // attributes.recycle();
            }
        }
    }

    // *************** GETTERS AND SETTERS ****************

    public int getActiveBgColor() {
        return activeBgColor;
    }

    public void setActiveBgColor(int activeBgColor) {
        this.activeBgColor = activeBgColor;
    }

    public int getActiveTextColor() {
        return activeTextColor;
    }

    public void setActiveTextColor(int activeTextColor) {
        this.activeTextColor = activeTextColor;
    }

    public int getInactiveBgColor() {
        return inactiveBgColor;
    }

    public void setInactiveBgColor(int inactiveBgColor) {
        this.inactiveBgColor = inactiveBgColor;
    }

    public int getInactiveTextColor() {
        return inactiveTextColor;
    }

    public void setInactiveTextColor(int inactiveTextColor) {
        this.inactiveTextColor = inactiveTextColor;
    }

    public int getSeparatorColor() {
        return separatorColor;
    }

    public void setSeparatorColor(int separatorColor) {
        this.separatorColor = separatorColor;
    }

    public int getTextSize() {
        return textSize;
    }

    public void setTextSize(int textSize) {
        this.textSize = textSize;
    }

    public float getCornerRadius() {
        return cornerRadius;
    }

    public void setCornerRadius(float cornerRadius) {
        this.cornerRadius = cornerRadius;
    }

    public float getToggleWidth() {
        return toggleWidth;
    }

    public void setToggleWidth(float toggleWidth) {
        this.toggleWidth = toggleWidth;
    }

    // *********** PRIVATE INSTANCE METHODS ************

    protected void activate(int position) {
        setColors(getToggleSwitchButton(position), activeBgColor, activeTextColor);
    }

    private void addToogleBtn(String text) {

        ToggleSwitchButton toggleSwitchButton = new ToggleSwitchButton(mContext);

        Text toggleBtnTxt = toggleSwitchButton.getTextView();
        toggleBtnTxt.setText(text);
        toggleBtnTxt.setTextSize(textSize, Text.TextSizeType.VP);
        DirectionalLayout.LayoutConfig layoutConfig = new LayoutConfig((int)toggleWidth,LayoutConfig.MATCH_CONTENT);
        if(toggleWidth == 0f){
            layoutConfig.weight = 1f;
        }
        toggleBtnTxt.setLayoutConfig(layoutConfig);

        ShapeElement shapeElement = new ShapeElement();
       shapeElement.setRgbColor(new RgbColor(separatorColor));
        toggleSwitchButton.getSeparator().setScrollbarBackgroundColor(new Color(separatorColor));
        toggleSwitchButton.getSeparator().setBackground(shapeElement);
        toggleSwitchButton.getTextView().setClickedListener(this);

        DirectionalLayout.LayoutConfig config = new LayoutConfig((int)toggleWidth,LayoutConfig.MATCH_PARENT);
        if(toggleWidth == 0f){
            config.weight = 1f;
        }
        toggleSwitchesContainer.addComponent(toggleSwitchButton.getView(),config);
        // Disable last added button
        disable(toggleSwitchesContainer.getChildCount() - 1);
    }

    private ShapeElement buildRect(ToggleSwitchButton toggleSwitchButton) {
        ShapeElement shapeElement = null;
        if (isFirst(toggleSwitchButton)) {
            shapeElement = new ShapeElement();
            shapeElement.setCornerRadiiArray(new float[]{cornerRadius, cornerRadius, 0, 0, 0, 0, cornerRadius, cornerRadius});
        }
        else if (isLast(toggleSwitchButton)) {
            shapeElement = new ShapeElement();
            shapeElement.setCornerRadiiArray(new float[]{0, 0, cornerRadius, cornerRadius, cornerRadius, cornerRadius, 0, 0});
//            return new RoundRectShape(
//                    new float[]{0, 0, cornerRadius, cornerRadius, cornerRadius, cornerRadius, 0, 0},
//                    null,
//                    null);
        }
        else {
            shapeElement = new ShapeElement();
            shapeElement.setCornerRadiiArray(new float[]{0, 0, 0, 0, 0, 0, 0, 0});
//            return new RoundRectShape(
//                    new float[]{0, 0, 0, 0, 0, 0, 0, 0},
//                    null,
//                    null);
        }
        return shapeElement;
    }

    protected void buildToggleButtons() {
        for (String label : mLabels)
            addToogleBtn(label);
    }

    protected void disable(int position) {
        setColors(getToggleSwitchButton(position), inactiveBgColor, inactiveTextColor);
    }

    protected void disableAll() {
        for (int i = 0; i < toggleSwitchesContainer.getChildCount(); i++)
            disable(i);
    }

    protected abstract boolean isActive(int position);

    protected int getNumButtons() {
        return getToggleSwitchesContainer().getChildCount();
    }

    protected DirectionalLayout getToggleSwitchesContainer() {
        return toggleSwitchesContainer;
    }

    protected int getToggleIndex(ToggleSwitchButton toggleSwitchButton) {
        return toggleSwitchesContainer.getChildIndex(toggleSwitchButton.getView());
    }

    protected ToggleSwitchButton getToggleSwitchButton(int position) {
        return new ToggleSwitchButton(toggleSwitchesContainer.getComponentAt(position));
    }

    protected boolean isLast(int position) {
        return position == getToggleSwitchesContainer().getChildCount() - 1;
    }

    @Override
    public void onClick(Component v) {
        DirectionalLayout toggleSwitchButton = (DirectionalLayout) v.getComponentParent();
        int position = toggleSwitchesContainer.getChildIndex(toggleSwitchButton);//.indexOfChild(toggleSwitchButton);
        onClickOnToggleSwitch(position);
    }

    protected abstract void onClickOnToggleSwitch(int position);

    protected void setColors(ToggleSwitchButton toggleSwitchButton, int bgColor, int textColor) {
        //ShapeDrawable sd = new ShapeDrawable(buildRect(toggleSwitchButton));
        //sd.getPaint().setColor(bgColor);
        ShapeElement shapeElement = buildRect(toggleSwitchButton);
        shapeElement.setRgbColor(new RgbColor(bgColor));
       // shapeElement.setCornerRadius(10);
       toggleSwitchButton.getView().setBackground(shapeElement);
       // toggleSwitchButton.getTextView().setSelectionColor(new Color(separatorColor));
        ShapeElement temp = new ShapeElement();
        temp.setRgbColor(new RgbColor(-separatorColor));
        toggleSwitchButton.getTextView().setBackground(temp);
        toggleSwitchButton.getTextView().setTextColor(new Color(textColor));
    }

    public void setLabels(ArrayList<String> labels) {
        if (labels == null || labels.isEmpty())
            throw new RuntimeException("The list of labels must contains at least 2 elements");
        mLabels = labels;
        toggleSwitchesContainer.removeAllComponents();
        buildToggleButtons();
    }

    public void setOnToggleSwitchChangeListener(OnToggleSwitchChangeListener onToggleSwitchChangeListener) {
        this.mOnToggleSwitchChangeListener = onToggleSwitchChangeListener;
    }

    public void notifyOnToggleChange(int position) {
        if (mOnToggleSwitchChangeListener != null)
            mOnToggleSwitchChangeListener.onToggleSwitchChangeListener(position, isActive(position));
    }

    public void setTogglePadding(int left, int top, int right, int bottom) {
        for (int i = 0; i < toggleSwitchesContainer.getChildCount(); i++) {
            ToggleSwitchButton toggleSwitchButton = new ToggleSwitchButton(toggleSwitchesContainer.getComponentAt(i));
            toggleSwitchButton.getTextView().setPadding(left, top, right, bottom);
        }
    }

    // **************** UTILS *****************

    private float dp2px(Context context, float dp) {
       // Resources resources = context.getResources();
        ResourceManager resourceManager = context.getResourceManager();
        DeviceCapability densityDpi = resourceManager.getDeviceCapability();
        //DisplayMetrics metrics = resources.getDisplayMetrics();
        //float px = dp * (metrics.densityDpi / 160f);
        float px = dp * (densityDpi.screenDensity / 160f);
        return px;
    }

    private boolean isFirst(ToggleSwitchButton toggleSwitchButton) {
        return toggleSwitchesContainer.getChildIndex(toggleSwitchButton.getView()) == 0;
    }

    private boolean isLast(ToggleSwitchButton toggleSwitchButton) {
        int lastPosition = toggleSwitchesContainer.getChildCount() - 1;
        return toggleSwitchesContainer.getChildIndex(toggleSwitchButton.getView()) == lastPosition;
    }
}
